package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public Result save(AddressBook addressBook) {
        //添加给地址设置userId
        Long userId= BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        //把以前设为默认地址的地址改成非默认地址
        addressBookMapper.noIsDefault(addressBook);
        //调用mapper保存新的收货地址,同时初始设置地址为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.insert(addressBook);
        return Result.success();
    }

    @Override
    public Result<List<AddressBook>> list() {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBooks=addressBookMapper.list(userId);
        return Result.success(addressBooks);
    }

    @Override
    public Result updateDefaultAddress(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        Long addressBookId = addressBook.getId();
        addressBook.setUserId(userId);
        //将所有地址设为非默认地址
        addressBookMapper.noIsDefault(addressBook);
        //将用户选定的地址设置为默认地址
        addressBook.setId(addressBookId);
        addressBook.setIsDefault(1);
        //修改地址为默认地址
        addressBookMapper.updateIsDefault(addressBook);
        return Result.success();
    }

    @Override
    public Result<AddressBook> getAddress(Long userId, Long addressId) {
        AddressBook addressBook=new AddressBook();
        addressBook.setUserId(userId);
        addressBook.setId(addressId);
        return Result.success(addressBookMapper.getAddress(addressBook));
    }

    @Override
    public Result delete(Long addressId) {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook=new AddressBook();
        addressBook.setId(addressId);
        addressBook.setUserId(userId);
        addressBookMapper.delete(addressBook);
        return Result.success();
    }

    @Override
    public Result<AddressBook> defaultAddress() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook=new AddressBook();
        addressBook.setIsDefault(1);
        addressBook.setUserId(userId);
        return Result.success(addressBookMapper.getAddress(addressBook));
    }

    @Override
    public Result update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
        return Result.success();
    }

}
